<?php
require_once SHMS_CORE_PATH."/shms_core_common.inc";
require_once SHMS_CORE_PATH."/shms_core_form_event.inc";
require_once SHMS_CORE_PATH."/shms_db_common.inc";
require_once SHMS_CORE_PATH."/shms_db_event.inc";

/**
 * List out the current events
 */
function shms_event_form_list($form,&$form_state){
  // load the events of this year
  $event_list = shms_core_db_load_assoc_all_match(SHMS_EVENT_TABLE, 'year', shms_get_current_academic_year(),'id');
  
  // check user access to decide
  global $user;
  $super_user_access = shms_user_with_super_access(); $user_pid = -1;
  
  /* purely for data showing.. note that this is a wrong method (correct way 
   * should be: you use theme function to add in the table here)
   */
  $header = array(t('Name'),t('Date'),t("Person in Charge"),t("Default CCA"),t("Options"));
  $rows = array();
  foreach($event_list as $event){
    $person_in_charge = shms_core_db_load_from_table(SHMS_PERSON_TABLE, 'id', $event['person_in_charge_id']);
    $has_edit_right = $super_user_access || ($user->uid == $person_in_charge['duid']);
    $rows[] = array(
      $event['name'], date("d/M/Y",$event['date']),$person_in_charge['full_name'], $event['default_cca_point'],
      $has_edit_right?l("Edit",SHMS_EVENT_PATH."/".$event['id']."/edit"):"",
    );
  }
  
  $form['list'] = array(
    "#markup" => theme("table",array("header" => $header, "rows"=> $rows)),
  );
  
  // and list using table
  return $form;
}

function shms_event_form_add($form,&$form_state){
  $form += shms_event_form_get_basic_struc() + array('submit'=>array(
    '#type' => "submit", '#value' => t("Add")
  ));
  
  return $form;
}

function shms_event_form_add_validate($form,&$form_state){
  shms_core_event_validate_chair_matric_and_change_it_to_person_id($form_state);
  shms_core_event_validate_name_exist($form_state);
}

function shms_event_form_add_submit($form,&$form_state){
  // add this event to the event list, the date is default to the current academic year
  
  // prepare the field for submission
  $values = $form_state['values'];$date = $values['date'];
  $event = array(
    "year"=>shms_get_current_academic_year(),
    "name"=>$values['name'],
    "description" =>  $values['description'],
    "date"  => mktime(0,0,0,$date['month'],$date['day'],$date['year']),
    "person_in_charge_id" => $values['person_in_charge_id'],
    "default_cca_point" => $values['default_cca_point'],
  );
  $ts = db_transaction();
  if(drupal_write_record(SHMS_EVENT_TABLE, $event) == SAVED_NEW){
    drupal_set_message("New event created, name: ".$event['name']);
  } else{
    drupal_set_message("Event Creation Failed. Please contact the technical support for help.","error");
    $ts->rollback();
  }
  // redirect to edit page
  $form_state['redirect'] = SHMS_EVENT_PATH."/".$event['id']."/edit";
}

function shms_event_form_add_member($form, &$form_state,$eid){
    if(!shms_event_form_verify_user_access($form_state,$eid)){
      drupal_set_message("Sorry you don't have access right to this page.","error");
      return array();
    }
    $form['eid'] = array('#type' => 'value','#value'=>$eid);
    $header = array("Full Name","Matric No.","Room Number");
    $members = shms_core_db_load_persons_by_blk('all');
    $form_state['member_info'] = $members;  // save the member info for future use
    $blkRows = array();
    
    // get the current list of participants
    $current_list = shms_core_db_get_person_info_list_from_eid($eid);
    foreach ($members as $pid => $record) {
      // filter out the existing members
      if(array_key_exists($record['pyid'], $current_list))  continue; 
      $blkRows[$record['room_number']{0}][$pid] = array(
        $record['full_name'],$record['matric_no'],$record['room_number'],
      );
    }
    ksort($blkRows);
    foreach($blkRows as $blk_letter => $rows){
      $form[$blk_letter] = array(
        '#type' => "fieldset",
        '#title'=> t("Block ".$blk_letter),
        '#collapsible'  => TRUE,
        '#collapsed'    => FALSE,
        'person'.$blk_letter => array(
          '#type' => "tableselect",
          '#header' => $header,
          "#options"=> $rows,
          '#empty' => t("Sorry There's no residence in this block yet as in the record."),
        ),
      );
    }
    shms_core_form_add_submit_button_for_basic($form, 21, "Confirm");
    return $form;
}

function shms_event_form_add_member_submit($form,&$form_state){
  $res = array(); $eid = $form_state['values']['eid'];
  foreach($form_state['values'] as $key => $record) {
    if(substr($key, 0,6) == "person") $res += array_filter($record);
  }
  
  $insert = db_insert(SHMS_EVENT_ATTENDANCE)->fields(array('pyid','eid'));
  $count = 0;
  foreach($res as $pid){
    $insert->values(array('eid'=>$eid,'pyid'=>$form_state['member_info'][$pid]['pyid']));
    $count++;
  }
  
  $insert->execute();
  drupal_set_message($count." people have been added to this event successfully.");
 
  $form_state['redirect'] = SHMS_EVENT_PATH."/$eid/edit";
}

function shms_event_form_edit($form, &$form_state, $eid){
  $event = shms_core_db_load_from_table(SHMS_EVENT_TABLE, 'id', $eid);
  if(empty($event)){
    drupal_set_message("The Event You're looking for doesn't exist.","error");
    return;
  }
  if(!shms_event_form_verify_user_access($form_state,$eid,$event)){
    drupal_set_message("Sorry you don't have access right to this page.","error");
    return array();
  }
  
  // transform the person_in_charge
  require_once SHMS_CORE_PATH."/shms_db_person.inc";
  $person_in_charge = shms_core_db_load_from_table(SHMS_PERSON_TABLE, 'id', $event['person_in_charge_id']);
  $event['person_in_charge'] = shms_put_person_str_from_info($person_in_charge);
  // transform the date
  $event['date'] = shms_core_get_date_arr_from_timestamp($event['date']);
  
  $form = shms_event_form_get_basic_struc();
  $form['eid'] = array("#type"=>"value","#value"=>$eid);
  
  shms_core_form_add_submit_button_for_basic($form, 8, "Update");
  $form['delete'] = array(
    '#type'   => "submit",
    '#value'  => t("Delete Event"),
    '#submit' => array('shms_event_form_delete'),
    '#attributes'=> array('onclick'=>"return confirm('Are you sure you want to preceed? This cannot be undone.')"),
    '#weight' => 9,
  );
  shms_add_default_value_for_fields($form, $event, !shms_user_with_super_access());
  
  // and add in the participant list
  $form += shms_event_form_person_in_group_table($eid);
  
  return $form;
}

function shms_event_form_edit_validate($form, &$form_state){
  shms_core_event_validate_chair_matric_and_change_it_to_person_id($form_state);
}

function shms_event_form_edit_submit($form, &$form_state){
  $values = $form_state['values'];$date = $values['date'];
  $event = array(
    "id"  =>$values['eid'],
    "name"=>$values['name'],
    "description" =>  $values['description'],
    "date"  => mktime(0,0,0,$date['month'],$date['day'],$date['year']),
    "person_in_charge_id" => $values['person_in_charge_id'],
    "default_cca_point" => $values['default_cca_point'],
  );
  $ts = db_transaction();
  if(drupal_write_record(SHMS_EVENT_TABLE, $event,array('id')) == SAVED_UPDATED){
    drupal_set_message("Event updated, name: ".$event['name']);
  } else{
    drupal_set_message("Event updating failed. Please contact the technical support for help.","error");
    $ts->rollback();
  }
}

/**
 * Thinking of really delete this event
 */
function shms_event_form_delete($form,&$form_state){
  $ts = db_transaction(); $eid = $form_state['values']['eid'];
  try{
    // first delete the list of participants
    db_delete(SHMS_EVENT_ATTENDANCE)->condition('eid',$eid)->execute();
    
    // then delete the event itself
    db_delete(SHMS_EVENT_TABLE)->condition('id',$eid)->execute();
  }catch(exception $e){
    $ts->rollback();
    watchdog("Exception: ".$e);
  }
  drupal_set_message("Event has been deleted");
  $form_state['redirect'] = SHMS_EVENT_PATH;  // then redirect back to the event path
}

function shms_event_person_form($form,&$form_state){
  // 1. load the pid
  global $user;
  $person = shms_core_db_load_from_table(SHMS_PERSON_TABLE, 'duid', $user->uid);
  if(empty($person)){
    drupal_set_message("Sorry you're not a residence here.","error");
    return array();
  }
  $pid = $person['id'];
  
  // 2. get a list of (pyid,year) pair
  $py_q = db_select(SHMS_PERSON_BY_YEAR_TABLE,"py");
  $py_q->condition("py.pid",$pid); $py_q->fields('py');
  $py_arr = $py_q->execute()->fetchAllAssoc('id',PDO::FETCH_ASSOC);
  
  $header = array("Event Name","Date","CCA Points");
  foreach($py_arr as $pyid=>$record){
    $py_event_query = db_select(SHMS_EVENT_ATTENDANCE,"ea");
    $py_event_query->condition("ea.pyid",$pyid); $py_event_query->innerJoin(SHMS_EVENT_TABLE,"e","ea.eid = e.id");
    $py_event_query->fields("e", array()); 
    $py_records = $py_event_query->execute()->fetchAllAssoc("id",PDO::FETCH_ASSOC);
    $rows = array(); $cca_total = 0;
    foreach($py_records as $py_record){
      $this_cca = $py_record['default_cca_point'];
      $cca_total += $this_cca;
      $rows[] = array(
        $py_record['name'],
        date("d M Y", $py_record['date']),
        $this_cca,
      );
    }
    
    $form['event'][$pyid] = array(
      '#type' => "fieldset",
      "#title"=> t("in Year ".$record['year']),
      '#children' => empty($rows)?
        "Sorry you didn't join any Event in that year.":
        "Current assigned cca points: ".$cca_total.
        theme("table",array("header"=>$header,"rows"=>$rows)),
    );
  }
  
  return $form;
  
  return $form;
}
